<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>手写一个Promise</title>
</head>
<body>
<script type="text/javascript">
class Promise2 {
	constructor (fn) {
		this.resolveQueue = [];
		this.rejectQueue = [];
		this.value = undefined;
		this.reason = undefined;
		this.status = 'pedding';

		const resolve = (value) => {
			if(this.status !== 'pedding') {
				return;
			}
			this.value = value;
			this.status = 'fulfilled';
			this.resolveQueue.forEach((itemfn) => {
				itemfn(this.value);
			})
		}
		const reject = (reason) => {
			if(this.status !== 'pedding') {
				return;
			}
			this.reason = reason;
			this.status = 'rejected';
			this.rejectQueue.forEach((itemfn) => {
				itemfn(this.reason);
			})
		}
		try {
			fn(resolve, reject);
		}catch(err) {
			reject(err);
		}
	}
	then(onFulfilled, onRejected) {//执行
		if(onFulfilled) {
			this.resolveQueue.push(onFulfilled);
		}
		if(onRejected) {
			this.rejectQueue.push(onRejected);
		}
		return this;
	}
}
const promise1 = new Promise2(function(resolve, reject) {//执行
	setTimeout(() => {
		reject(11);
	})
});
console.log(promise1);
promise1.then((value) => {
	console.log('a1', value);
}, (reason) => {
	console.log('b1', reason);
}).then((value) => {
	console.log('a2', value);
}, (reason) => {
	console.log('b2', reason);
});
</script>
<script type="text/javascript">
</script>
</body>
</html>